package com.ita.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.ita.dao.CustomerDao;
import com.ita.pojo.Customer;

@Repository(value = "customerDao")
public class CustomerDaoImpl implements CustomerDao {

	@PersistenceContext(name = "unit")
	private EntityManager manager;

	@Override
	public Customer addUser(Customer c) {

		manager.persist(c);
		return c;
	}

	@Override
	public Customer update(Customer c) {

		Customer customer = manager.find(Customer.class, c.getId());
		customer.setAge(c.getAge());
		customer.setPassword(c.getPassword());
		customer.setUname(c.getUname());
		manager.flush();
		return customer;
	}

	@Override
	public Customer delete(String id) {

		Customer customer = manager.find(Customer.class, id);
		manager.remove(customer);
		manager.close();
		return customer;
	}

	@Override
	public List<Customer> findAll() {

		Query query = manager.createQuery("from Customer c");
		@SuppressWarnings("unchecked")
		List<Customer> list = query.getResultList();
		return list;
	}

	@Override
	public Customer findByName(String uname) {

		Query query = manager.createQuery("from Customer c where c.uname=:uname");
		Customer c= (Customer) query.setParameter("uname", uname).getSingleResult();
		return c;
	}

}
